﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DataAccess.Models;
using DataAccess.Repository;

namespace KPI
{
	public partial class MailOutbox : BasePage
	{
		private IMailRepository _MailRepository;
		private List<MailMessage> _DataSource;
		private int _TotalRecords;

		/// <summary>
		/// 当前页
		/// </summary>
		public int PageIndex
		{
			get
			{
				if(ViewState["PageIndex"] == null)
				{
					return 1;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		/// <summary>
		/// 总记录数
		/// </summary>
		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		/// <summary>
		/// 总页数
		/// </summary>
		public int TotalPages
		{
			get
			{
				var data = _DataSource == null ? this.DataSource : _DataSource;

				if(data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 1;

				if(totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if(totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if(totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		/// <summary>
		/// 每页显示记录数
		/// </summary>
		public int PageSize
		{
			get
			{
				return 20;
			}
		}

		/// <summary>
		/// 每页绑定的数据源
		/// </summary>
		public List<MailMessage> DataSource
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				if(_MailRepository == null)
				{
					_MailRepository = new MailRepository();
				}

				_DataSource = _MailRepository.GetSentMailList(TheCurrentLoginUser.UserName, pageIndex, pageSize, out totalRecords);

				this.TotalRecords = totalRecords;

				return _DataSource;
			}
		}

		protected void Page_Init(object sender, EventArgs e)
		{
			if(TheCurrentLoginUser == null)
			{
				Response.Redirect("~/Login.aspx");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
			}
		}

		protected void btnDelete_Click(object sender, EventArgs e)
		{
			List<int> mailIDs = new List<int>();

			foreach(ListViewDataItem item in listMails.Items)
			{
				var chbSelect = item.FindControl("chbSelect") as CheckBox;

				if(chbSelect.Checked)
				{
					var id = Convert.ToInt32(listMails.DataKeys[item.DataItemIndex].Value);

					mailIDs.Add(id);
				}
			}

			if(mailIDs.Count > 0)
			{
				if(_MailRepository == null)
				{
					_MailRepository = new MailRepository();
				}

				if(_MailRepository.DeleteOutboxMail(mailIDs))
				{
					ShowMessage("删除成功.", false);
				}
				else
				{
					ShowMessage("删除时遇到错误,请稍后再试或联系管理员.", true);
				}
			}
		}

		/// <summary>
		/// 翻页事件(上一页,下一页,跳转)
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void lbtnPaging_Click(object sender, EventArgs e)
		{
			if(((LinkButton)sender).CommandArgument.Equals("pre"))
			{
				this.PageIndex -= 1;
				if(PageIndex < 1)
				{
					PageIndex = 1;
				}

				txtGotoPage.Text = PageIndex.ToString();
			}
			else if(((LinkButton)sender).CommandArgument.Equals("next"))
			{
				this.PageIndex += 1;
				if(PageIndex > TotalPages)
				{
					PageIndex = TotalPages;
				}

				txtGotoPage.Text = PageIndex.ToString();
			}
			else if(((LinkButton)sender).CommandArgument.Equals("goto"))
			{
				var gotoPageIndex = this.PageIndex;

				if(int.TryParse(txtGotoPage.Text.Trim(), out gotoPageIndex))
				{
					if(gotoPageIndex > 0)
					{
						this.PageIndex = gotoPageIndex;

						if(gotoPageIndex > TotalPages)
						{
							this.PageIndex = TotalPages;
							this.txtGotoPage.Text = this.PageIndex.ToString();
							this._DataSource = null;
						}
					}
				}
			}
		}

		protected void listMails_ItemDataBound(object sender, ListViewItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				var dataItem = e.Item.DataItem as MailMessage;

				if(dataItem != null)
				{
					var lMailSubject = e.Item.FindControl("lMailSubject") as Literal;
					var lMailSender = e.Item.FindControl("lMailSender") as Literal;
					var lMailContent = e.Item.FindControl("lMailContent") as Literal;
					var lMailSentTime = e.Item.FindControl("lMailSentTime") as Literal;
					var hlMailDetail = e.Item.FindControl("hlMailDetail") as HyperLink;
					var imgMailAtt = e.Item.FindControl("imgMailAtt") as Image;

					lMailSubject.Text = dataItem.MailSubject.Length > 26 ? dataItem.MailSubject.Substring(0, 25) + "..." : dataItem.MailSubject;
					lMailSender.Text = dataItem.MailFrom != null ? dataItem.MailFrom : string.Empty;
					var content = CommonHelper.HtmlStripTags(dataItem.MailContent);
					lMailContent.Text = content.Length > 30 ? content.Substring(0, 29) + "..." : content;
					lMailSentTime.Text = dataItem.MailSendTime.ToString("yyyy-MM-dd HH:mm");
					hlMailDetail.NavigateUrl = "~/MailDetail.aspx?id=" + dataItem.MailID.ToString();

					if(string.IsNullOrWhiteSpace(dataItem.MailAttFile))
					{
						imgMailAtt.Visible = false;
					}
					else
					{
						imgMailAtt.Visible = true;
					}
				}
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			//if(IsPostBack)
			{
				var data = _DataSource == null ? this.DataSource : _DataSource;

				BindData();

				var currentPageIndex = this.PageIndex;
				var totalPages = this.TotalPages;

				this.lPageIndex.Text = totalPages > 0 ? currentPageIndex.ToString() : "0";
				this.lPageCount.Text = totalPages.ToString();
				this.lTotalRecords.Text = "总记录: " + TotalRecords.ToString();

				this.lbtnPrePage.Enabled = currentPageIndex > 1 && currentPageIndex <= totalPages;
				this.lbtnNextPage.Enabled = currentPageIndex < totalPages;

				if(!this.lbtnPrePage.Enabled)
				{
					lbtnPrePage.CssClass = "disable";
				}
				else
				{
					lbtnPrePage.CssClass = string.Empty;
				}

				if(!this.lbtnNextPage.Enabled)
				{
					lbtnNextPage.CssClass = "disable";
				}
				else
				{
					lbtnNextPage.CssClass = string.Empty;
				}
			}
		}

		protected void Page_UnLoad(object sender, EventArgs e)
		{
			if(_MailRepository != null)
			{
				((IDisposable)_MailRepository).Dispose();
			}
		}

		/// <summary>
		/// 绑定数据
		/// </summary>
		private void BindData()
		{
			var data = _DataSource == null ? this.DataSource : _DataSource;

			listMails.DataSource = data;
			listMails.DataBind();
		}
	}
}